package com.zq.assistant.func.okhttp.download;

import com.squareup.okhttp.Interceptor;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Response;
import com.squareup.okhttp.ResponseBody;
import com.zq.assistant.func.okhttp.FileTransferListener;

import java.io.IOException;

import okio.Buffer;
import okio.BufferedSource;
import okio.ForwardingSource;
import okio.Okio;
import okio.Source;
import okio.Timeout;

/**
 * Created by zhangqiang on 17-6-6.
 */

public class ProgressResponseBody extends ResponseBody {

    public static OkHttpClient addFileTransferListener(OkHttpClient okHttpClient, final FileTransferListener fileTransferListener) {

        OkHttpClient cloneHttpClient = okHttpClient.clone();
        cloneHttpClient.interceptors().add(new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {

                Response originalResponse = chain.proceed(chain.request());

                return originalResponse.newBuilder()
                        .body(new ProgressResponseBody(originalResponse.body(), fileTransferListener))
                        .build();
            }
        });
        return cloneHttpClient;
    }

    private ResponseBody responseBody;
    private FileTransferListener fileTransferListener;

    private ProgressResponseBody(ResponseBody responseBody, FileTransferListener fileTransferListener) {
        this.responseBody = responseBody;
        this.fileTransferListener = fileTransferListener;
    }

    @Override
    public MediaType contentType() {
        return responseBody.contentType();
    }

    @Override
    public long contentLength() throws IOException {
        return responseBody.contentLength();
    }

    @Override
    public BufferedSource source() throws IOException {
        return Okio.buffer(source(responseBody.source()));
    }


    /**
     * 读取，回调进度接口
     *
     * @param source Source
     * @return Source
     */
    private Source source(Source source) {

        return new ForwardingSource(source) {

            //当前读取字节数
            long totalBytesRead = 0L;

            @Override
            public long read(Buffer sink, long byteCount) throws IOException {

                long bytesRead = super.read(sink, byteCount);
                //增加当前读取的字节数，如果读取完成了bytesRead会返回-1
                if (bytesRead != -1) {

                    totalBytesRead += bytesRead;
                    //回调，如果contentLength()不知道长度，会返回-1
                    fileTransferListener.onTransfer(responseBody.contentLength(), totalBytesRead);
                }
                return bytesRead;
            }
        };
    }
}
